import React, {useEffect, useState} from 'react';
import {Button, Form, Input, Modal, Select, Table, TableProps} from 'antd';
import type {Candidate} from "@/types/resp/candidate";
import candidateApi from '@/api/candidateApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";


interface CandidateSelectorProps {
  visible: boolean;
  onCandidateSelected: (selectedCandidate: { candidateId?: number; candidateName?: string; }) => void;
  onCloseCandidateSelector: () => void;
}

const CandidateSelector: React.FC<CandidateSelectorProps> = ({visible, onCandidateSelected, onCloseCandidateSelector}) => {

  const [candidateSelectorForm] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    candidateSelectorForm.resetFields();
  };

  const [data, setData] = useState<Candidate[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<Candidate>> = await candidateApi.find(candidateSelectorForm.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<Candidate> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<Candidate>['columns'] = [
    {title: '用户名', dataIndex: 'username', key: 'username'},
    {title: '姓名', dataIndex: 'name', key: 'name'},
    {title: '密码', dataIndex: 'password', key: 'password'},
    {title: '性别', key: 'gender', render: (_, record) => (
        <span>
        {(function () {
          if (record.gender === 1) return '男';
          else if (record.gender === 2) return '女';
          else return '未知';
        })()}
      </span>
      ),
    },
    {title: '出生日期', key: 'birthDate', render: (_, record) => (
      <div>{record.birthDate.format('YYYY-MM-DD')}</div>
    )},
    {title: '联系电话', dataIndex: 'contactPhone', key: 'contactPhone'},
    {title: '邮箱', dataIndex: 'email', key: 'email'},
    {title: '省', dataIndex: 'provinceName', key: 'province'},
    {title: '市', dataIndex: 'cityName', key: 'city'},
    {title: '区', dataIndex: 'areaName', key: 'area'},
    {title: '家庭地址', dataIndex: 'address', key: 'address'},
  ];

  const handleRowDoubleClick = (row: Candidate) => {
    onCandidateSelected({
      candidateId: row.id,
      candidateName: row.name,
    })
  };

  const selectorFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onCloseCandidateSelector}>关闭</Button>
    </div>
  );

  useEffect(() => {
    if (visible) {
      onSearch();
    }
  }, [visible]);


  return (
    <Modal title={"应聘者基本信息选择器(双击行选中)"} open={visible} onCancel={onCloseCandidateSelector}
        width={'var(--modal-width)'} footer={selectorFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      <Form form={candidateSelectorForm} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="username" label="用户名">
          <Input maxLength={64} placeholder="请输入用户名"/>
        </Form.Item>
        <Form.Item name="name" label="姓名">
          <Input maxLength={64} placeholder="请输入姓名"/>
        </Form.Item>
        <Form.Item name="gender" label="性别">
          <Select placeholder="请选择性别" options={[
            { value: 1, label: <span>男</span> },
            { value: 2, label: <span>女</span> }
          ]} style={{width: 'var(--select-width)'}} />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
      </Form>
      <Table<Candidate> columns={columns} dataSource={data} size="small" rowKey={record => record.id}
                         pagination={{ position: ["bottomCenter"] }}
                         onRow={(row) => ({
                           onDoubleClick: (event) => {
                             event.preventDefault();
                             handleRowDoubleClick(row);
                           },
                         })}/>
    </Modal>
  );
};

export default CandidateSelector;
